package front;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.db_backend;

import mt.middle;


/**
 * Servlet implementation class ForumController
 */
public class ForumController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public ForumController() {
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet!");
		
		handleReqest(request,response);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doPost!");
		
		handleReqest(request, response);
	}

	private void handleReqest(HttpServletRequest req, HttpServletResponse res) {
		PrintWriter out = null;
		try {
			out = res.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		HttpSession session = req.getSession(true);
		middle m = new middle(new db_backend());
		

		if(req.getParameter("action").equals("logout")){
			session.invalidate();
			System.out.println("Logged out!");
			try {
				res.sendRedirect("index.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(req.getParameter("action").equals("register")){
			
			String name = req.getParameter("name");
			String email = req.getParameter("email");
			String password = req.getParameter("password");
			
			if(name.equals("") || email.equals("") || password.equals("") || name.equals(" ") || email.equals(" ") || password.equals(" ")){
				out.println("<p> Registration failed!</p>");
				out.println("Back to <a href='register.jsp'>registration</a>");
			}
			else{
				try {
					User newUser = new User(0, name, email, password);
					newUser.Create();
					
					out.println("<p> Registration successful!</p>");
					out.println("Back to <a href='index.jsp'>index!</a>");
					
				} catch (Exception e) {
					System.out.println("Password hash fail?");
					e.printStackTrace();
				}
			}
		}
		
		if(req.getParameter("action").equals("login")){
			String username = req.getParameter("username");
			String password = req.getParameter("password");
		
			boolean check = false;
			try {
				check = m.login(username, password);
			
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(check){
				System.out.println("Check!");
				User user = m.getUser(username);
				
				session.setAttribute("user", user);
				try {
				if(req.getParameter("subForumID")!= null){
					if(req.getParameter("threadID")!= null){
						res.sendRedirect("thread.jsp?subForumID="+req.getParameter("subForumID")+"&threadID="+req.getParameter("threadID"));
					}else{
						res.sendRedirect("subforum.jsp?subForumID="+req.getParameter("subForumID"));
					}
				}else{
					res.sendRedirect("index.jsp");
				}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			else{
				System.out.println("Not Check!");
				out.print("failed login!");
				out.println("Back to <a href='index.jsp'>index!</a>");
			}
		}
		
		if(req.getParameter("action").equals("createThread")){
			if(req.getParameter("name").equals("")||req.getParameter("name")==null){
				try {
					session.setAttribute("noName", true);
					session.setAttribute("retCont",req.getParameter("content"));
					res.sendRedirect("createThread.jsp?subForumID="+req.getParameter("subForumID"));
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			else if(req.getParameter("content").equals(""))
			{
				try{
				session.setAttribute("noCont", true);
				session.setAttribute("retName", req.getParameter("name"));
				res.sendRedirect("createThread.jsp?subForumID="+req.getParameter("subForumID"));
				}catch (IOException e){
					e.printStackTrace();
				}
			}
			else{
				int subforumid = Integer.parseInt(req.getParameter("subForumID"));
				String NameOfThread = req.getParameter("name");
				String Content = req.getParameter("content");
				
				User user = (User) session.getAttribute("user");
				
				SubForum sf = m.getSubforum(subforumid);
				
				Thread newThread = new Thread(subforumid, NameOfThread, user.getUserID());
				newThread.Create();
				
				Post newPost = new Post(newThread.getThreadID(), user.getUserID(), Content);
				newPost.Create();
				
				user.incrementNumberOfPosts();
				
				session.setAttribute("user", user);
				
				sf.incrementNumberOfThreads();
				
				try {
					res.sendRedirect("index.jsp");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		if(req.getParameter("action").equals("makePost")){
			User user = (User) session.getAttribute("user");
			String content = req.getParameter("content");
			int threadID = Integer.parseInt(req.getParameter("threadID"));
			
			m.getThread(threadID).incrementThreadReplies();
			Post newPost = new Post(threadID, user.getUserID(), content);
			newPost.Create();
			
			user.incrementNumberOfPosts();
			
			session.setAttribute("user", user);
		
			try {
				res.sendRedirect("thread.jsp?subForumID="+req.getParameter("subForumID") +"&threadID="+threadID+"#link"+req.getParameter("postNR"));
			} catch (IOException e) {
				System.out.println("Error!");
				e.printStackTrace();
			}
		}
		if(req.getParameter("action").equals("editPost")){
			int postID = Integer.parseInt(req.getParameter("postID"));
			m.getPost(postID).editContent(req.getParameter("content"));
		
			try {
				res.sendRedirect("thread.jsp?subForumID="+req.getParameter("subForumID") +"&threadID="+req.getParameter("threadID")+"#link"+req.getParameter("postNR"));
			} catch (IOException e) {
				System.out.println("Error!");
				e.printStackTrace();
			}
		}

		if(req.getParameter("action").equals("profile")){

			int userID = Integer.parseInt(req.getParameter("userID"));
			
			User user = new beans.Hax().getUser(userID);
			
			session.setAttribute("user", user);

			session.setAttribute("threadsByUser", user.getAllThreadsByUser().toArray());
			session.setAttribute("PMsent", user.getAllPMsSentByUser().toArray());
			session.setAttribute("PMreceive", user.getAllPMsToUser().toArray());
			try {
				res.sendRedirect("user.jsp");
				
			} catch (IOException e) {
				System.out.println("Error!");
				e.printStackTrace();
			}
		}
		
		if(req.getParameter("action").equals("sendPM")){
			ArrayList<User> users = m.getAllUsers();
			session.setAttribute("users", users.toArray());
			
			try {
				res.sendRedirect("sendPM.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(req.getParameter("action").equals("createPM")){
			int FromUserID = ((User)session.getAttribute("user")).getUserID();
			int ToUserID = Integer.parseInt(req.getParameter("to"));
			String content = req.getParameter("content");
			
			PM newPM = new PM(0, FromUserID, ToUserID, new Timestamp(System.currentTimeMillis()), content);
			newPM.Create();
			
			try {
				res.sendRedirect("index.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
